﻿using System;
using System.Text;
using System.Web;
using System.Web.Caching;
using CY_MVC.Core;
using CY_MVC.Utility;


namespace CY_MVC.HttpHandlers
{
    public class ResourceController : BaseController
    {
        protected override void Page_Load()
        {
            DateTime DateLastModified = DateTime.MinValue;

            if (!string.IsNullOrEmpty(Request.Headers["If-Modified-Since"]))
            {
                DateTime.TryParse(Request.Headers["If-Modified-Since"], out DateLastModified);
            }

            if (!string.IsNullOrEmpty(Request.QueryString["csskey"]))
            {
                if (DateLastModified.AddHours(StaticConfig.JsCssCacheHour) < DateTime.Now)
                {
                    byte[] Bytes = GetResourceByKey(Request.QueryString["csskey"]);
                    if (Bytes != null)
                    {
                        Response.Cache.SetExpires(DateTime.Now.AddHours(StaticConfig.JsCssCacheHour));
                        Response.Cache.SetMaxAge(TimeSpan.FromHours(StaticConfig.JsCssCacheHour));
                        Response.Cache.SetLastModified(DateTime.Now);
                        Response.Cache.SetCacheability(HttpCacheability.Public);

                        Response.AddHeader("Content-Type", "text/css");
                        Response.ContentType = "text/css";

                        if (StaticConfig.GzipLength != 0 && HttpGzip.CanGZip() && Bytes.Length > StaticConfig.GzipLength)
                        {
                            Response.AppendHeader("Content-Encoding", "gzip");
                            Bytes = HttpGzip.GzipStr(Bytes);
                        }
                        Response.BinaryWrite(Bytes);
                    }
                }
                else
                {
                    Response.ClearHeaders();
                    Response.Cache.SetLastModified(DateLastModified);
                    Response.Status = "304 Not Modified";
                    Response.AppendHeader("Content-Length", "0");
                }
            }
            else if (!string.IsNullOrEmpty(Request.QueryString["jskey"]))
            {
                if (DateLastModified.AddHours(StaticConfig.JsCssCacheHour) < DateTime.Now)
                {
                    byte[] Bytes = GetResourceByKey(Request.QueryString["jskey"]);
                    if (Bytes != null)
                    {
                        Response.Cache.SetExpires(DateTime.Now.AddHours(StaticConfig.JsCssCacheHour));
                        Response.Cache.SetMaxAge(TimeSpan.FromHours(StaticConfig.JsCssCacheHour));
                        Response.Cache.SetLastModified(DateTime.Now);
                        Response.Cache.SetCacheability(HttpCacheability.Public);

                        Response.AddHeader("Content-Type", "application/x-javascript");
                        Response.ContentType = "application/x-javascript";

                        if (StaticConfig.GzipLength != 0 && HttpGzip.CanGZip() && Bytes.Length > StaticConfig.GzipLength)
                        {
                            Response.AppendHeader("Content-Encoding", "gzip");
                            Bytes = HttpGzip.GzipStr(Bytes);
                        }
                        Response.BinaryWrite(Bytes);
                    }
                }
                else
                {
                    Response.ClearHeaders();
                    Response.Cache.SetLastModified(DateLastModified);
                    Response.Status = "304 Not Modified";
                    Response.AppendHeader("Content-Length", "0");
                }
            }
        }

        private byte[] GetResourceByKey(string p_Key)
        {
            byte[] res;
            if (!DataCache.GetCache(p_Key, out res))
            {
                var m_HWU = new HttpWebUtility();
                var response = string.Empty;
                var paths = ResourceHelper.Resources[p_Key];
                foreach (string path in paths)
                {
                    m_HWU.Url = new Uri((path.IndexOf("http://", StringComparison.OrdinalIgnoreCase) == 0 ||
                            path.IndexOf("https://", StringComparison.OrdinalIgnoreCase) == 0)
                               ? path
                               : HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + path);
                    m_HWU.Request();
                    response += m_HWU.Response();
                }
                res = Encoding.UTF8.GetBytes(response);
                DataCache.SetCache(p_Key, res, Cache.NoAbsoluteExpiration, TimeSpan.FromHours(StaticConfig.JsCssCacheHour), CacheItemPriority.NotRemovable);
            }
            return res.Length > 0 ? res : null;
        }
    }
}